<script setup>
import SchedulingFrame from '../components/SchedulingFrame.vue';
import { ref, toRefs, reactive, onBeforeMount } from 'vue'
import { ElMessageBox } from 'element-plus'
import DialogYaml from '../components/DialogYaml.vue' // codeMirror 从DialogYaml组件引用
import { storeToRefs } from 'pinia'
import { useItem } from '../../store';
import { createCronJobHandler as createItem, updateCronJobHandler as updateItem } from '../../api/cronjob.js';
import { obj2Yaml } from '../../utils/utils';
import { useRouter } from 'vue-router'
const router = useRouter()
const props = defineProps({
  method: {
    type: String,
    default: 'Create'
  },
  resourceType: {
    type: String,
    default: 'CronJob'
  },
  cronJobItem: {
    type: Object
  }
})
const useItemer = useItem()
const showDetail = ref(false)
const yamlContent = ref('')
const data = reactive({
  cronjobItem: {
    apiVersion: "batch/v1",
    kind: "CronJob",
    metadata: "",
    spec: {
      schedule: "*/5 * * * *",
      concurrencyPolicy: "Allow",
      suspend: false,
      successfulJobsHistoryLimit: 3,
      failedJobsHistoryLimit: 1,
      jobTemplate: {
        spec: {
          template: {}
        }
      }
    }
  }
})

const submitRollback = (msg) => {
  ElMessageBox.confirm(
    msg,
    '执行结果',
    {
      confirmButtonText: '查看列表',
      cancelButtonText: '继续编辑',
      type: 'success',
      draggable: true,
    }
  ).then(() => {
    router.replace({
      path: '/cronjob/list',
      query: {
        clusterId: useItemer.clusterId,
        namespace: useItemer.namespace
      }
    })
  }).catch(() => {
    console.info("继续编辑")
    router.replace({
      path: '/cronjob/edit',
      query: {
        clusterId: useItemer.clusterId,
        namespace: useItemer.namespace,
        name: useItemer.item.metadata.name,
        method: "Update"
      }
    })
  })
}
const submit = (tag) => {
  data.cronjobItem.spec.jobTemplate.spec.template = useItemer.item.spec.template
  data.cronjobItem.metadata = useItemer.item.metadata
  if(tag == 'yaml') { // json转yaml
    const yamlData = obj2Yaml(data.cronjobItem)
    yamlContent.value = yamlData
    showDetail.value = true
  } else {
    const postData = {
      clusterId: useItemer.clusterId,
      namespace: useItemer.namespace,
      item: data.cronjobItem,
    }
    if (props.method != 'Update') {
      createItem(postData).then((response) => {
        submitRollback(response.data.message)
      })
    } else {
      updateItem(postData).then((response) => {
        console.log(props.method)
        submitRollback(response.data.message)
      })
    }
  }
}
// 返回更新方式的类型
const concurrencyPolicy = [
  {
    value: "Allow",
    label: "允许并发调度"
  },
  {
    value: "Forbid",
    label: "禁止并发调度"
  },
  {
    value: "Replace",
    label: "替换上次任务"
  }
]
// 返回更新方式的类型
const restartPolicy = [
  {
    value: "OnFailure",
    label: "失败时重启"
  },
  {
    value: "Never",
    label: "从不重启"
  }
]

onBeforeMount(() => {
  useItemer.item.spec.template.spec.restartPolicy = "OnFailure"
  if (props.method == 'Create') {
    delete useItemer.item.spec.replicas // 删除副本数字段
  } else{
    data.cronjobItem = props.cronJobItem
  }
})
const { clusterId, namespace, item } = storeToRefs(useItem())
const { cronjobItem } = toRefs(data)
</script>

<template>
  <SchedulingFrame @submit="submit" :method="props.method" :resource-type="props.resourceType">
    <template #strategy>
      <el-col :span="6">
        <el-form-item title='值可以是绝对数字(例如:5)或所需 Pod 的百分比(例如:10%)' label="调度周期" prop="">
          <el-input v-model.trim="cronjobItem.spec.schedule" style="width:180px"/>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="并发策略" prop="cronjobItem.spec.concurrencyPolicy">
            <el-select v-model="cronjobItem.spec.concurrencyPolicy" style="width:180px" placeholder="并发策略">
                <el-option
                v-for="s in concurrencyPolicy"
                :key="s.value"
                :label="s.label"
                :value="s.value"
                >
                </el-option>
            </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="重启策略" prop="spec.template.spec.restartPolicy">
            <el-select v-model="item.spec.template.spec.restartPolicy" style="width:180px" placeholder="并发策略">
                <el-option
                v-for="s in restartPolicy"
                :key="s.value"
                :label="s.label"
                :value="s.value"
                >
                </el-option>
            </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
          <el-form-item title='值可以是绝对数字(例如:5)或所需 Pod 的百分比(例如:10%)' label="暂停调度">
            <el-switch v-model="cronjobItem.spec.suspend"></el-switch>
          </el-form-item>
      </el-col>
    </template>
    <template #specialConfig>
      <el-col :span="6">
          <el-form-item title='值可以是绝对数字(例如:5)或所需 Pod 的百分比(例如:10%)' label="失败任务保留数量" prop="cronjobItem.spec.failedJobsHistoryLimit">
            <el-input-number v-model="cronjobItem.spec.failedJobsHistoryLimit" :min="1"/>
          </el-form-item>
      </el-col>
      <el-col :span="6">
          <el-form-item title='值可以是绝对数字(例如:5)或所需 Pod 的百分比(例如:10%)' label="成功任务保留数量" prop="cronjobItem.spec.successfulJobsHistoryLimit">
            <el-input-number v-model="cronjobItem.spec.successfulJobsHistoryLimit" :min="1"/>
          </el-form-item>
      </el-col>
    </template>
  </SchedulingFrame>
  <DialogYaml
  :cluster-id="clusterId"
  :namespace="namespace"
  :yaml-content="yamlContent"
  :show-dialog="showDetail"
  @close-dialog-handler="(val) => { showDetail = val }"
  >
  </DialogYaml>
</template>

<style scoped>
</style>
